const express = require('express');
const router = express.Router();
const { sequelize, User } = require('../../models');
const { Op, where } = require('sequelize');
const { NotFound } = require('http-errors');
const { success, failure } = require('../../utils/responses');
const { initOrderStream, broadcastOrderCount } = require('../../streams/count-order')
/**
 * 统计用户性别
 *
 * Get /admin/charts/sex
 *
 * **/
router.get('/sex', async function (req, res) {
  try {
    const male = await User.count({ where: { sex: 0 } });
    const female = await User.count({ where: { sex: 1 } });
    const unknow = await User.count({ where: { sex: 2 } });
    const data = [
      { value: male, name: '男性' },
      { value: female, name: '女性' },
      { value: unknow, name: '未选择' },
    ];
    success(res, '查询性别成功', data);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 统计每个月用户数量
 * GET /admin/charts/user
 * */

router.get('/user', async function (req, res) {
  try {
    const [results] = await sequelize.query(
      "SELECT DATE_FORMAT(`createdAt`, '%Y-%m') AS `month`, COUNT(*) AS `value` FROM `Users` GROUP BY `month` ORDER BY `month` ASC"
    );
    const data = {
      months: [],
      values: [],
    };
    results.forEach((item) => {
      data.months.push(item.month);
      data.values.push(item.value);
    });
    success(res, '查询性别成功', data);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * sse 统计每个月订单数量
 * get /admin/charts/stream_order
 * */ 
router.get('/stream_order', async(req, res) => {
  try {
    await initOrderStream(res, req);
    await broadcastOrderCount()
  } catch (error) {
     failure(res, error)
  }
})

module.exports = router;
